const express = require("express")
const router = express.Router()
const { users } = require("../models/modules")
const { generateToken } = require("../util/jwt")
const { ACCESS_KEY, REFRESH_KEY } = require("../config/keys")
const { checkAuth } = require("../middleware/token")
// const { generateAccessToken, generateRefreshToken } = require("../models/modules")

router.post("/login", async (req, res) => {
    let { name, password } = req.body
    // 1. 查找用户
    const user = await users.find({ name, password });
    if (user.length > 0) {
        const pyload = {
            name: user[0].name,
            password: user[0].password
        }
        const accessToken = generateToken(pyload, ACCESS_KEY, "3s")
        const refreshToken = generateToken(pyload, REFRESH_KEY, "60s")
        res.send({
            code: 200,
            msg: "登录成功",
            token: {
                accessToken,
                refreshToken
            }
        })
    } else {
        res.send({
            code: 403,
            msg: "账号或密码错误"
        })
    }
})

router.get("/list", checkAuth(ACCESS_KEY), async(req, res) => {
    let data = await users.find({})
    res.send({
        code: 200,
        msg: "查询成功",
        data
    })
})

router.get("/refresh_token", checkAuth(REFRESH_KEY), async (req, res) => {
    const { claim } = req
    const pyload = {
        name: claim.name,
        password: claim.password
    }
    const accessToken = generateToken(pyload, ACCESS_KEY, '3s')
    // const refreshToken = generateToken(pyload, REFRESH_KEY, 120)
    res.send({
        code: 200,
        msg: "刷新成功",
        token: {
            accessToken,
            // refreshToken
        }
    })
})



module.exports = router